package com.hongru.aspect;

import com.hongru.api.SysLogApi;
import com.hongru.aspect.annotation.Log;
import com.hongru.constant.DictConstant;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 日志切面处理类
 *
 * @author Yaming
 * @create 2019-01-24
 */
@Aspect
@Component
public class LogAspect {

    @Lazy
    @Resource
    private SysLogApi sysLogApi;

    /**
     * 日志切入点
     */
    @Pointcut("@annotation(com.hongru.aspect.annotation.Log)")
    public void logPointCut() {
    }

    @Before("logPointCut()")
    public void Before(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Method method = currentMethod(joinPoint, methodName);
        Log log = method.getAnnotation(Log.class);
        if (methodName.contains(DictConstant.OPERATE_TYPE_EDIT)) {
            sysLogApi.putUpdate(joinPoint, methodName, log.name(), log.value());
        }
    }

    @AfterReturning("logPointCut()")
    public void doAfter(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Method method = currentMethod(joinPoint, methodName);
        Log log = method.getAnnotation(Log.class);
        if (methodName.contains(DictConstant.OPERATE_TYPE_ADD)) {
            sysLogApi.putSave(joinPoint, methodName, log.name(), log.value());
        }
        if (methodName.contains(DictConstant.OPERATE_TYPE_DELETE)) {
            sysLogApi.putDelete(joinPoint, methodName, log.name(), log.value(),log.className());
        }

    }
    /**
     * 获取当前执行的方法
     *
     * @param joinPoint  连接点
     * @param methodName 方法名称
     * @return 方法
     */
    private Method currentMethod(JoinPoint joinPoint, String methodName) {
        /**
         * 获取目标类的所有方法，找到当前要执行的方法
         */
        Method[] methods = joinPoint.getTarget().getClass().getMethods();
        Method resultMethod = null;
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                resultMethod = method;
                break;
            }
        }
        return resultMethod;
    }


}
